package com.ruoyi.common.tongyi;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class TongYi {

    public static String getTongYi(String message, String apiKey) throws IOException {
        // 创建请求体
        RequestBody requestBody = new RequestBody(
                "qwen-plus",
                new Message[] {
                        new Message("system", "You are a helpful assistant."),
                        new Message("user", message)
                }
        );

        // 将请求体转换为 JSON
        Gson gson = new Gson();
        String jsonInputString = gson.toJson(requestBody);

        // 创建 URL 对象
        URL url = new URL("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为 POST
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
        httpURLConnection.setRequestProperty("Accept", "application/json");

        String auth = "Bearer " + apiKey;
        httpURLConnection.setRequestProperty("Authorization", auth);

        // 启用输入输出流
        httpURLConnection.setDoOutput(true);

        // 写入请求体
        try (OutputStream os = httpURLConnection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 获取响应码
        int responseCode = httpURLConnection.getResponseCode();

        // 读取响应体并解析
        try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }

            // 解析 JSON 并提取 content
            JsonObject jsonResponse = JsonParser.parseString(response.toString()).getAsJsonObject();
            JsonArray choices = jsonResponse.getAsJsonArray("choices"); //响应中有一个名为 "choices" 的数组
            if (choices != null && choices.size() > 0) {
                JsonObject firstChoice = choices.get(0).getAsJsonObject();
                JsonObject messageObj = firstChoice.getAsJsonObject("message");
                return messageObj.getAsJsonPrimitive("content").getAsString();
            }
        }

        return null; // 如果没有找到合适的 content 则返回 null 或者考虑抛出异常
    }

}
